﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Fetches.Fetch.Utils.FileHosting
{
    public class HostFileItem
    {
        private string _uniqueId;

        /// <summary>
        ///     资源的来源url
        /// </summary>
        public Uri Uri { get; set; }

        /// <summary>
        ///     部分情况下资源随时间变动，使用这个字段来做区分
        /// </summary>
        public List<KeyValuePair<string, string>> FeatureKvs { get; set; } = new List<KeyValuePair<string, string>>();

        /// <summary>
        ///     需要存储的数据
        /// </summary>
        public byte[] Data { get; set; }

        /// <summary>
        ///     该Url该情景下的唯一ID
        /// </summary>
        public string UniqueId
        {
            get
            {
                if (string.IsNullOrEmpty(_uniqueId))
                {
                    var sourceUrl = new StringBuilder();
                    sourceUrl.AppendLine(Uri.OriginalString);
                    foreach (var kv in FeatureKvs)
                    {
                        sourceUrl.AppendLine($"{kv.Key}={kv.Value}");
                    }

                    _uniqueId = HashHelper.Md5(sourceUrl.ToString());
                }

                return _uniqueId;
            }
        }


        /// <summary>
        ///     返回的凭据格式为http://src.store.io/{uri.Host}/{uri.AbsolutePath}?id=UniqueId
        ///     实际存储维护着uniqueId到内容hash的映射，并根据uniqueId来获得二进制数据
        ///     通过这种与实际数据无关的url实现异步查重写入数据
        ///     返回凭据Query前面的部分是辅助人类识别的，存储并不依赖该信息
        ///     src.store.io我本身是hosts指向本机，然后用candy反代到FetchesDeploy.ScalableFactory的
        /// </summary>
        /// <returns></returns>
        public string GetReceiptUrl()
        {
            return $"http://src.store.io/{Uri.Host}{Uri.AbsolutePath}?id={UniqueId}";
        }
    }
}